﻿using System;
using System.Collections.Generic;
using System.Linq;
using NOSDC.Pocos;
using System.Linq.Expressions;
using NOSDC.Entities;
using System.Data.Objects;

namespace NOSDC.Repositories.Articles
{
    public class ArticleRepository : IArticleRepository
    {
        private readonly NOSDCContext _context;

        //TODO: Refactor for testing. Implement Interfaces
        public ArticleRepository()
        {
            _context = new NOSDCContext();
        }

        public int CreateArticle(Article article)
        {
            _context.Articles.AddObject(article);
            return _context.SaveChanges();
        }

        public int UpdateArticle(Article article)
        {
            _context.Articles.Attach(article);
            var articleEntry = _context.ObjectStateManager.GetObjectStateEntry(article);
            articleEntry.SetModified();
            _context.ObjectStateManager.ChangeObjectState(article, System.Data.EntityState.Modified);
            return _context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }

        public bool DeleteArticle(Article article)
        {
            _context.DeleteObject(article);
            return _context.SaveChanges() > 0;
        }

        public Article GetArticleByID(int id)
        {
            return GetArticleByID(id, false);
        }

        public Article GetArticleByID(int id, bool getComments)
        {
            return getComments ? _context.Articles.Include("Comments").FirstOrDefault(a => a.ArticleID.Equals(id)) : _context.Articles.FirstOrDefault(a => a.ArticleID.Equals(id));
        }

        public IEnumerable<Article> GetArticles(Expression<Func<Article, bool>> expression)
        {
            return _context.Articles.Where(expression).ToList();
        }

        public IEnumerable<Article> GetAllArticles()
        {
            return _context.Articles.ToList();
        }

        public IEnumerable<Article> GetFrontpageArticles()
        {
            return _context.Articles.Include("Comments")
                                    .Where(a => a.Status.StatusID == 1)
                                    .OrderByDescending(a => a.DatePosted)
                                    .Take(5)
                                    .ToList();
        }
    }
}
